package com.alibaba.moco.springboot;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.entity.ContentType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.moco.gitlab.GitlabApiUtil;
import com.alibaba.moco.gitlab.GitlabFileResVo;
/**
 * 静态资源拦截器   加载js以及html等等
 * @author wb-lj240895
 *
 */
public class ResourceInterceptor implements HandlerInterceptor {

	private static final String RESOURCE_PERFIX = "webapp";

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

		String uri = request.getRequestURI();
		if ("/".equals(uri))
			uri = "/index.html";
		GitlabFileResVo source = GitlabApiUtil.getFileContent(RESOURCE_PERFIX + uri);

		if (source == null) {
			return true;
		}
		ContentType.TEXT_HTML.getMimeType();
		String content = source.getContent();
		if (uri.endsWith(".html")) {
			response.setContentType("text/html");
		} else if (uri.endsWith(".js")) {
			response.setContentType("application/javascript");
		} else if (uri.endsWith(".css")) {
			response.setContentType("text/css");
		} else if (uri.endsWith(".png")) {
			response.setContentType("image/png");
		} else if (uri.endsWith(".woff")) {
			response.setContentType("application/x-font-woff");
		} else if (uri.endsWith(".woff2")) {
			response.setContentType("application/octet-stream");
		} else if (uri.endsWith(".ttf")) {
			response.setContentType("application/x-font-ttf");
		}
		// response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(content);
		response.getWriter().flush();
		response.getWriter().close();
		return false;
	}

}
